<template>
  <el-drawer
    v-model="visible"
    title="消息通知"
    direction="rtl"
    size="400px"
    class="notification-drawer"
  >
    <template #header>
      <div class="drawer-header">
        <h3>消息通知</h3>
        <div class="header-actions">
          <el-button 
            text 
            @click="markAllAsRead"
            :disabled="unreadCount === 0"
          >
            全部已读
          </el-button>
          <el-button 
            text 
            @click="clearAll"
            :disabled="notifications.length === 0"
          >
            清空
          </el-button>
        </div>
      </div>
    </template>

    <div class="notification-content">
      <!-- 筛选标签 -->
      <div class="filter-tabs">
        <div 
          v-for="tab in filterTabs" 
          :key="tab.key"
          class="filter-tab"
          :class="{ active: activeFilter === tab.key }"
          @click="activeFilter = tab.key"
        >
          {{ tab.label }}
          <el-badge 
            v-if="tab.count > 0" 
            :value="tab.count" 
            class="tab-badge"
          />
        </div>
      </div>

      <!-- 通知列表 -->
      <div class="notification-list">
        <div 
          v-for="notification in filteredNotifications" 
          :key="notification.id"
          class="notification-item"
          :class="{ 'unread': !notification.read }"
          @click="handleNotificationClick(notification)"
        >
          <div class="notification-icon">
            <el-icon :class="`icon-${notification.type}`">
              <component :is="getNotificationIcon(notification.type)" />
            </el-icon>
          </div>
          
          <div class="notification-content">
            <div class="notification-title">{{ notification.title }}</div>
            <div class="notification-message">{{ notification.message }}</div>
            <div class="notification-meta">
              <span class="notification-time">{{ formatTime(notification.timestamp) }}</span>
              <span v-if="notification.category" class="notification-category">
                {{ notification.category }}
              </span>
            </div>
          </div>
          
          <div class="notification-actions">
            <el-button 
              circle 
              size="small" 
              @click.stop="removeNotification(notification.id)"
            >
              <el-icon><Close /></el-icon>
            </el-button>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="filteredNotifications.length === 0" class="empty-state">
          <el-icon class="empty-icon"><Bell /></el-icon>
          <p>暂无{{ activeFilterLabel }}消息</p>
        </div>
      </div>

      <!-- 加载更多 -->
      <div v-if="hasMore" class="load-more">
        <el-button 
          text 
          @click="loadMore"
          :loading="loading"
        >
          加载更多
        </el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import {
  Bell, Close, Message, Warning, InfoFilled,
  CircleCheckFilled, CircleCheck, User, Document
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'update-count'])

// 响应式数据
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const activeFilter = ref('all')
const loading = ref(false)
const hasMore = ref(true)

// 模拟通知数据
const notifications = ref([
  {
    id: '1',
    type: 'system',
    title: '系统通知',
    message: '您的课程《Vue3实战开发》已更新新章节',
    timestamp: new Date(Date.now() - 1000 * 60 * 30),
    read: false,
    category: '课程更新'
  },
  {
    id: '2',
    type: 'exam',
    title: '考试提醒',
    message: '《JavaScript基础》考试将在明天下午2点开始',
    timestamp: new Date(Date.now() - 1000 * 60 * 60 * 2),
    read: false,
    category: '考试安排'
  },
  {
    id: '3',
    type: 'task',
    title: '任务完成',
    message: '恭喜您完成了今日学习任务！',
    timestamp: new Date(Date.now() - 1000 * 60 * 60 * 4),
    read: true,
    category: '学习任务'
  },
  {
    id: '4',
    type: 'social',
    title: '好友动态',
    message: '张三发布了新的学习笔记',
    timestamp: new Date(Date.now() - 1000 * 60 * 60 * 6),
    read: true,
    category: '社交动态'
  },
  {
    id: '5',
    type: 'achievement',
    title: '成就解锁',
    message: '您获得了"学习达人"徽章！',
    timestamp: new Date(Date.now() - 1000 * 60 * 60 * 24),
    read: false,
    category: '成就系统'
  }
])

// 计算属性
const unreadCount = computed(() => {
  return notifications.value.filter(n => !n.read).length
})

const filterTabs = computed(() => [
  { key: 'all', label: '全部', count: notifications.value.length },
  { key: 'unread', label: '未读', count: unreadCount.value },
  { key: 'system', label: '系统', count: notifications.value.filter(n => n.type === 'system').length },
  { key: 'exam', label: '考试', count: notifications.value.filter(n => n.type === 'exam').length },
  { key: 'task', label: '任务', count: notifications.value.filter(n => n.type === 'task').length }
])

const activeFilterLabel = computed(() => {
  const tab = filterTabs.value.find(t => t.key === activeFilter.value)
  return tab ? tab.label : '全部'
})

const filteredNotifications = computed(() => {
  let filtered = notifications.value
  
  if (activeFilter.value === 'unread') {
    filtered = filtered.filter(n => !n.read)
  } else if (activeFilter.value !== 'all') {
    filtered = filtered.filter(n => n.type === activeFilter.value)
  }
  
  return filtered.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))
})

// 方法
const getNotificationIcon = (type) => {
  const iconMap = {
    system: InfoFilled,
    exam: Warning,
    task: CircleCheck,
    social: User,
    achievement: CircleCheckFilled,
    message: Message,
    document: Document
  }
  return iconMap[type] || Bell
}

const formatTime = (timestamp) => {
  const now = new Date()
  const time = new Date(timestamp)
  const diff = now - time
  
  const minutes = Math.floor(diff / (1000 * 60))
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (minutes < 1) return '刚刚'
  if (minutes < 60) return `${minutes}分钟前`
  if (hours < 24) return `${hours}小时前`
  if (days < 7) return `${days}天前`
  
  return time.toLocaleDateString('zh-CN')
}

const handleNotificationClick = (notification) => {
  if (!notification.read) {
    notification.read = true
    updateCount()
  }
  
  // 根据通知类型跳转到相应页面
  switch (notification.type) {
    case 'exam':
      // 跳转到考试页面
      break
    case 'task':
      // 跳转到任务页面
      break
    case 'social':
      // 跳转到社交页面
      break
    default:
      break
  }
}

const markAllAsRead = () => {
  notifications.value.forEach(n => n.read = true)
  updateCount()
  ElMessage.success('已标记全部消息为已读')
}

const clearAll = () => {
  notifications.value = []
  updateCount()
  ElMessage.success('已清空所有消息')
}

const removeNotification = (id) => {
  const index = notifications.value.findIndex(n => n.id === id)
  if (index > -1) {
    notifications.value.splice(index, 1)
    updateCount()
  }
}

const loadMore = () => {
  loading.value = true
  
  // 模拟加载更多数据
  setTimeout(() => {
    // 这里应该调用API加载更多通知
    loading.value = false
    hasMore.value = false
  }, 1000)
}

const updateCount = () => {
  emit('update-count', unreadCount.value)
}

// 监听器
watch(unreadCount, (newCount) => {
  emit('update-count', newCount)
}, { immediate: true })
</script>

<style lang="scss" scoped>
.notification-drawer {
  :deep(.el-drawer__header) {
    margin-bottom: 0;
    padding: 20px 20px 0 20px;
  }
  
  :deep(.el-drawer__body) {
    padding: 0;
  }
}

.drawer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
  }
  
  .header-actions {
    display: flex;
    gap: 8px;
  }
}

.notification-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.filter-tabs {
  display: flex;
  padding: 20px 20px 0 20px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  margin-bottom: 0;
  
  .filter-tab {
    position: relative;
    padding: 8px 16px;
    cursor: pointer;
    border-radius: 6px;
    transition: all 0.3s ease;
    color: var(--el-text-color-secondary);
    font-size: 14px;
    
    &:hover {
      background: var(--el-fill-color-light);
      color: var(--el-text-color-primary);
    }
    
    &.active {
      background: var(--el-color-primary-light-9);
      color: var(--el-color-primary);
    }
    
    .tab-badge {
      margin-left: 4px;
    }
  }
}

.notification-list {
  flex: 1;
  overflow-y: auto;
  padding: 0 20px;
}

.notification-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px 0;
  border-bottom: 1px solid var(--el-border-color-extra-light);
  cursor: pointer;
  transition: background 0.3s ease;
  
  &:hover {
    background: var(--el-fill-color-extra-light);
    margin: 0 -20px;
    padding-left: 20px;
    padding-right: 20px;
  }
  
  &.unread {
    position: relative;
    
    &::before {
      content: '';
      position: absolute;
      left: -20px;
      top: 50%;
      transform: translateY(-50%);
      width: 4px;
      height: 20px;
      background: var(--el-color-primary);
      border-radius: 2px;
    }
    
    .notification-title {
      font-weight: 600;
    }
  }
}

.notification-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  
  .el-icon {
    font-size: 20px;
    
    &.icon-system {
      color: var(--el-color-info);
      background: var(--el-color-info-light-9);
    }
    
    &.icon-exam {
      color: var(--el-color-warning);
      background: var(--el-color-warning-light-9);
    }
    
    &.icon-task {
      color: var(--el-color-success);
      background: var(--el-color-success-light-9);
    }
    
    &.icon-social {
      color: var(--el-color-primary);
      background: var(--el-color-primary-light-9);
    }
    
    &.icon-achievement {
      color: var(--el-color-danger);
      background: var(--el-color-danger-light-9);
    }
  }
}

.notification-content {
  flex: 1;
  min-width: 0;
}

.notification-title {
  font-size: 14px;
  color: var(--el-text-color-primary);
  margin-bottom: 4px;
  @include text-ellipsis(1);
}

.notification-message {
  font-size: 13px;
  color: var(--el-text-color-secondary);
  line-height: 1.4;
  margin-bottom: 8px;
  @include text-ellipsis(2);
}

.notification-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  color: var(--el-text-color-placeholder);
}

.notification-category {
  padding: 2px 6px;
  background: var(--el-fill-color-light);
  border-radius: 4px;
  font-size: 11px;
}

.notification-actions {
  opacity: 0;
  transition: opacity 0.3s ease;
  
  .notification-item:hover & {
    opacity: 1;
  }
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  color: var(--el-text-color-placeholder);
  
  .empty-icon {
    font-size: 48px;
    margin-bottom: 16px;
    opacity: 0.5;
  }
  
  p {
    margin: 0;
    font-size: 14px;
  }
}

.load-more {
  padding: 20px;
  text-align: center;
  border-top: 1px solid var(--el-border-color-extra-light);
}
</style>
